package com.leef.oauth.data.api;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.leef.oauth.data.api.interceptor.AuthenticationInterceptor;
import com.leef.oauth.data.convert.FastJsonConverterFactory;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

/**
 * Created by IWALL on 2017/2/21.
 * Singleton
 */
public class RetrofitApi {

//    private static final String API_BASE_URL = "https://andaily.com/spring-oauth-server/";
    private static final String API_BASE_URL = "http://112.74.164.90/";
    private static OkHttpClient.Builder mHttpClientBuilder = new OkHttpClient().newBuilder();

    private static AuthenticationInterceptor mAuthenticationInterceptor;
    private static OkHttpClient mHttpClient = null;
    private static Retrofit mRetrofit = null;

    private RetrofitApi() {
    }

    public static void updateToken(String token) {
        if (mAuthenticationInterceptor != null) {
            mAuthenticationInterceptor.setToken(token);
        }
    }

    private static Retrofit.Builder mRetrofitBuilder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(FastJsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create());

    private static OkHttpClient getHttpClient() {
        if (mHttpClient == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            if (!mHttpClientBuilder.interceptors().contains(interceptor)) {
                mHttpClientBuilder.addInterceptor(interceptor);
            }
            mAuthenticationInterceptor = new AuthenticationInterceptor();
            if (!mHttpClientBuilder.interceptors().contains(mAuthenticationInterceptor)) {
                mHttpClientBuilder.addInterceptor(mAuthenticationInterceptor);
            }
            mHttpClient = mHttpClientBuilder.build();
        }
        return mHttpClient;
    }

    private static Retrofit getRetrofit() {
        if (mRetrofit == null) {
            mRetrofitBuilder.client(getHttpClient());
            mRetrofit = mRetrofitBuilder.build();
        }
        return mRetrofit;
    }

    public static <S> S createService(Class<S> serviceClass) {
        return getRetrofit().create(serviceClass);
    }
}
